<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <el-row>

        <el-col :span="24">

          <div class="postInfo-container">
            <el-row>
              <el-col :span="8">
                <el-form-item label-width="140px" label="成员*:" class="postInfo-container-item">
                  <el-select v-model="postForm.user_id" filterable size="mini" placeholder="请选择">
                    <el-option
                      v-for="item in ownerOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label-width="140px" label="等级:" class="postInfo-container-item">
                  <el-select v-model="postForm.level" filterable size="mini" placeholder="请选择">
                    <el-option
                      v-for="item in levelOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label-width="140px" label="所在城市:" class="postInfo-container-item">
                  <el-input v-model="postForm.school" auto-complete="off" size="mini"/>
                </el-form-item>
              </el-col>
            </el-row>

          </div>
        </el-col>
      </el-row>
      <el-form-item label-width="140px" label="荣誉">
        <el-input :rows="1" v-model="postForm.honer" type="textarea" class="article-textarea" autosize placeholder="请输入团队描述"/>
      </el-form-item>
      <el-form-item label-width="140px" label="经验">
        <el-input :rows="1" v-model="postForm.experience" type="textarea" class="article-textarea" autosize placeholder="请输入团队描述"/>
      </el-form-item>
      <el-form-item label-width="140px" label="描述">
        <el-input :rows="1" v-model="postForm.desc" type="textarea" class="article-textarea" autosize placeholder="请输入团队描述"/>
      </el-form-item>
      <el-form-item label-width="140px" label="角色">
        <el-checkbox-group
          v-model="postForm.elements"
          :min="0">
          <el-checkbox v-for="tag in allTags" :label="tag.value" :key="tag.value">{{ tag.label }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm()">新增
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="listLoading" :data="page.records" border fit highlight-current-row style="width: 100%" height="300">
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="生产者昵称">
        <template slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-edit" @click="modifyProducer(scope.row)">
            {{ scope.row.user_nickname }}
          </el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" label="团队" width="100px">
        <template slot-scope="scope">
          {{ scope.row.team_name }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="所在城市" width="100px">
        <template slot-scope="scope">
          {{ scope.row.city }}
        </template>
      </el-table-column>

      <el-table-column width="120px" align="center" label="荣誉">
        <template slot-scope="scope">
          <span>{{ scope.row.honer }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" align="center" label="总得分">
        <template slot-scope="scope">
          <span>{{ scope.row.score_total }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.create_time }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="Actions" width="240">
        <template slot-scope="scope">
          <el-button type="danger" size="small" icon="el-icon-delete" @click="delProd(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="page.recordsTotal>0" :total="page.recordsTotal" :page.sync="page.pageNum" :page-sizes="[50, 100]" :limit.sync="page.pageSize" @pagination="getList" />

  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import Sticky from '@/components/Sticky' // 粘性header组件
import { fetchOwnerList } from '@/api/user'
import { fetchAllElements } from '@/api/elements'
import { fetchList, createProducer, updateProducer, deleteProducer } from '@/api/producer'
import Pagination from '@/components/Pagination'

const defaultForm = {
  id: undefined,
  user_id: '',
  school: '',
  honer: '',
  experience: '',
  level: 0,
  team_id: '',
  desc: '',
  elements: []
}

export default {
  name: 'MembersDetail',
  components: { Sticky, Pagination },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    currentId: {
      type: Number,
      default: undefined
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      listLoading: false,
      checkedTag: [],
      allTags: [],
      postForm: Object.assign({}, defaultForm),
      ownerOptions: [],

      eleComponents: [0],
      tagComponents: [0],
      tagOptions: [],
      elementOptions: [],
      teamOptions: [],
      videoTypeOptions: [],
      dialogImageUrl: '',
      dialogVisible: false,
      stateOptions: [{ 'label': '有效', 'value': 0 }, { 'label': '无效', 'value': 1 }],
      levelOptions: [{ 'label': '普通成员', 'value': 0 }, { 'label': 'Leader', 'value': 1 }],
      videoSourceOptions: [{ value: 1, label: '单品' }, { value: 2, label: '样片' }],
      loading: false,
      rules: {
        name: [{ required: true, trigger: 'blur', validator: validateRequire }]
      },
      tempRoute: {},
      page: { pageNum: 1, pageSize: 100, pageTotal: 0, recordsTotal: 0, records: [] }
    }
  },
  computed: {
    authHeader() {
      const token = getToken()
      return { 'Authorization': token }
    },
    lang() {
      return this.$store.getters.language
    }
  },
  watch: {
    currentId: {
      handler: function(val, oldval) {
        // this.clearPostForm()
        console.log(val, oldval)
        if (val !== undefined && val > 0) {
          this.fetchData(val)
        }
      },
      deep: true
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.currentId
      this.fetchData(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
    this.fetchUsers()
    this.fetchElements()
  },
  methods: {
    delProd(producer) {
      this.myConfirm('确定从团队删除该成员, 是否继续?', this._delProd, producer, '已取消操作')
    },
    _delProd(producer) {
      deleteProducer({ producerId: producer.id, type: 'removeFromTeam' }).then(response => {
        const r = response.data
        if (r.code === 0) {
          this.$message({ message: '操作成功', type: 'success' })
          this.getList()
        } else {
          this.$message({ message: r.msg, type: 'error' })
        }
      })
    },
    fetchElements() {
      fetchAllElements().then(response => {
        this.allTags = response.data.data.elements
        console.log(this.allTags)
      })
    },
    clearPostForm() {
      this.postForm = Object.assign({}, defaultForm)
    },
    fetchUsers() {
      fetchOwnerList().then(response => {
        this.ownerOptions = response.data.data.users
      })
    },
    modifyProducer(producer) {
      this.postForm.id = producer.id
      this.postForm.user_id = producer.user_id
      this.postForm.school = producer.school
      this.postForm.honer = producer.honer
      this.postForm.experience = producer.experience
      this.postForm.leve = producer.leve
      this.postForm.team_id = producer.team_id
      this.postForm.desc = producer.desc
      this.postForm.elements = producer.elements
    },
    getList() {
      this.fetchData(this.currentId)
    },
    fetchData(id) {
      fetchList({ team_id: id, pageNum: this.page.pageNum, pageSize: this.page.pageSize }).then(response => {
        const data = response.data
        if (data.code !== 0) {
          this.$message.error(data.msg)
        }
        this.page = data.data
        this.listLoading = false
      }).catch(err => {
        console.log(err)
      })
    },
    submitForm() {
      this.postForm.team_id = this.currentId
      this.postForm.display_time = parseInt(this.display_time / 1000)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          let requestFunc = createProducer
          let msg = '团队创建成功'
          if (this.postForm.id !== undefined && this.postForm.id > 1) {
            requestFunc = updateProducer
            msg = '团队修改成功'
          }
          requestFunc(this.postForm).then(response => {
            const r = response.data
            if (r.code === 0) {
              this.$notify({
                title: '成功',
                message: msg,
                type: 'success',
                duration: 2000
              })
              this.clearPostForm()
              this.getList()
            } else {
              this.$message({ message: r.msg, type: 'error' })
            }
          })
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/styles/mixin.scss";
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
</style>
